/**
 * 首页
 */
import React, { PureComponent } from "react";
import {
    StyleSheet,
    View,
    ScrollView,
    Text,
    TouchableOpacity,
    TextInput,
    Image,
    Keyboard,
    FlatList, TouchableWithoutFeedback
} from "react-native";
import actions from "../../models/actions";
import { connect } from "react-redux";
import image from "../../assets/image";
import {
    screenWidth,
    screenHeight,
    statusBarHeight,
    safeAreaBottomHeight,
    LoginToken,
    UserInfo
} from "../../util/AdapterUtil";
import PasswordModal from "../../components/paykeybordview/PasswordModal";
import ItemView from "../../components/ItemView";
import NavigationService from "../../components/NavigationService";
import MD5 from "react-native-md5";
import * as requestApi from "../../util/requestApi";

class HomeScreen extends PureComponent {
    constructor(props) {
        super(props);
        this.state = {
            index: 1, //支付方式
            money: "",
            token: "",
            showCompanySearch: false, //展示汽配公司搜索界面
            companydata: [], //展示汽配公司列表
            currentCompanyID: "",
            companyName: "",
        };
    }
    componentWillUnmount() {}

    componentDidMount() {
        //从全局里面拿
        this.setState({ token: global.token });
        //从缓存文件里面拿
        this.getDataFromStorage(); //读取token
    }

    //读取token
    getDataFromStorage = async () => {
        global.storage
            .load({
                key: LoginToken
            })
            .then(ret => {
                this.setState({ token: ret });
            })
            .catch(err => {
                this.setState({ token: global.token });
            });
    };

    render() {
        const {companyName,money} = this.state
        const userInfo = this.props.userInfo ? this.props.userInfo : this.props.token;
        let imageHash = null
        if (userInfo){
            imageHash = userInfo.urlAddr
        }
        return (
            <View style={{ flex: 1, backgroundColor: "#F9F9F9" }}>
                <TouchableWithoutFeedback
                    onPress={() => {
                        this.setState({
                            showCompanySearch: false
                        });
                    }}>
                    <View
                        style={{
                            zIndex: 800,
                            backgroundColor: "#fff",
                            paddingTop: statusBarHeight,
                            width: "100%",
                            flexDirection: "row",
                            alignItems: "center",
                            height: 50 + statusBarHeight
                        }}
                    >
                        <TouchableOpacity
                            style={{ marginLeft: 15 }}
                            onPress={this.personSetting.bind(this)}
                        >
                            <Image
                                resizeMode={'cover'}
                                source={imageHash ? { uri: "http://cdn.traceche.com/" + imageHash} : image.avatar_default}
                                style={{ borderRadius: 20, width: 40, height: 40 }}
                            />
                        </TouchableOpacity>

                        <View
                            style={{
                                flex: 1,
                                justifyContent: "center",
                                alignItems: "center",
                                flexDirection: "row",
                                height: 50
                            }}
                        >
                            <Text style={[styles.titleStyle, { marginRight: 55 }]}>
                                辛巴支付
                            </Text>
                        </View>
                    </View>
                </TouchableWithoutFeedback>
                <View
                    style={{
                        marginTop: 8,
                        backgroundColor: "#fff",
                        flexDirection: "row",
                        height: 60,
                        paddingLeft: 20,
                        paddingRight: 15,
                        alignItems: "center",
                        justifyContent: "center"
                    }}
                >
                    <Text style={{ color: "#606060", fontSize: 18, fontWeight: "bold" }}>
                        收款方
                    </Text>

                    <TextInput
                        ref={e => {
                            this.searchTextInput = e;
                        }}
                        style={{
                            padding: 0,
                            textAlign: "right",
                            color: "#202020",
                            fontSize: 16,
                            flex: 1,
                            height: 40
                        }}
                        placeholder={"请输入汽配商名称"}
                        maxLength={18}
                        value={companyName}
                        onChangeText={text => {
                            if (text != null && text.length >= 18) {
                                Toast.show("名称不能超过18个字符", 1000);
                            } else if (
                                typeof text == "undefined" ||
                                text == null ||
                                text == ""
                            ) {
                                this.setState({ showCompanySearch: false });
                            }
                            this.setState({
                                currentCompanyID: null,
                                companyName: text
                            });

                            this._getCompanyList(text)
                        }}
                        returnKeyType={"search"}
                        onSubmitEditing={(event) => {
                            this._getCompanyList(event.nativeEvent.text);
                        }}/>

                    {companyName.trim().length === 0 ? null : (
                        <TouchableOpacity
                            style={{marginLeft:8, width: 15, height: 15 }}
                            onPress={() => {
                                this.clearTextInput();
                            }}
                        >
                            <Image
                                style={{
                                    width: 15,
                                    height:15,
                                }}
                                source={image.clear}
                            />
                        </TouchableOpacity>
                    )}
                </View>
                {/*查询汽配商列表界面*/}
                {this.state.showCompanySearch &&
                this.state.companydata &&
                this.state.companydata.length > 0
                    ? this.showCompanySearchView()
                    : null}

                <View
                    style={{
                        marginLeft: 15,
                        height: 1,
                        backgroundColor: "#ccc",
                        transform: [{ scaleY: 0.5 }]
                    }}
                />

                <View
                    style={{
                        backgroundColor: "#fff",
                        flexDirection: "row",
                        height: 60,
                        paddingLeft: 20,
                        paddingRight: 15,
                        alignItems: "center",
                        justifyContent: "center"
                    }}
                >
                    <Text style={{ color: "#606060", fontSize: 18, fontWeight: "bold" }}>
                        总金额
                    </Text>

                    {money.trim().length === 0 ?
                        <TouchableOpacity style={{flex: 1,height: 40}}
                                          onPress={() => {
                                              this.MoneyTextInput && this.MoneyTextInput.focus();
                                          }}/>
                        :
                        (<TouchableOpacity
                            style={{flex: 1,marginLeft:8, height: 40,alignItems: "flex-end",
                                justifyContent: "center"}}
                            onPress={() => {
                                this.MoneyTextInput && this.MoneyTextInput.focus();
                            }}>
                            <Text style={{color: "#ccc", fontSize: 16}}>￥</Text>
                        </TouchableOpacity>
                    )}
                    <TextInput
                        ref={e => {
                            this.MoneyTextInput = e;
                        }}
                        style={{
                            padding: 0,
                            textAlign: "right",
                            color: "#202020",
                            fontSize: 16,
                            height: 40
                        }}
                        placeholder={"￥"}
                        keyboardType={"decimal-pad"}
                        selectionColor={"#4A90E2"}
                        value={money}
                        maxLength={15}
                        onChangeText={text => {
                            if (text != null && text.length >= 15) {
                                Toast.show("总金额不能超过15位数", 1000);
                            } else {
                                let newmoney = money;
                                try {
                                    let a = Number(text);
                                    if (isNaN(a)) {
                                        this.setState({
                                            money: newmoney.trim()
                                        });
                                    } else {
                                        this.setState({
                                            money: text.trim()
                                        });
                                    }
                                } catch (e) {
                                    this.setState({
                                        money: newmoney.trim()
                                    });
                                }
                            }
                        }}
                    />

                    {money.trim().length === 0 ? null : (
                        <TouchableOpacity
                            style={{marginLeft:8, width: 15, height: 15, alignItems: "center",
                                justifyContent: "center"}}
                            onPress={() => {
                                this.clearMoneyTextInput();
                            }}>
                            <Image
                                style={{
                                    width: 15,
                                    height:15,
                                }}
                                source={image.clear}
                            />
                        </TouchableOpacity>
                    )}
                </View>

                <View
                    style={{
                        marginLeft: 15,
                        height: 1,
                        backgroundColor: "#ccc",
                        transform: [{ scaleY: 0.5 }]
                    }}
                />

                <View
                    style={{
                        backgroundColor: "#fff",
                        flexDirection: "row",
                        height: 60,
                        paddingLeft: 20,
                        paddingRight: 15,
                        alignItems: "center"
                    }}
                >
                    <Text style={{ color: "#606060", fontSize: 18, fontWeight: "bold" }}>
                        支付方式
                    </Text>

                    <View style={{ flex: 1 }} />

                    <ItemView
                        style={{ width: 85, height: 34, marginLeft: 10 }}
                        ref={ItemView1 => {
                            this.ItemView1 = ItemView1;
                        }}
                        isSelect={this.state.index == 1}
                        dic={"直接支付"}
                        onPress={() => {
                            this.ItemView2 && this.ItemView2._unSelect();
                            this.setState({
                                index: 1
                            });
                        }}
                    />
                    <ItemView
                        style={{ width: 85, height: 34, marginLeft: 10 }}
                        ref={ItemView2 => {
                            this.ItemView2 = ItemView2;
                        }}
                        isSelect={this.state.index == 2}
                        dic={"货到付款"}
                        onPress={() => {
                            this.ItemView1 && this.ItemView1._unSelect();
                            this.setState({
                                index: 2
                            });
                        }}
                    />
                </View>

                <View
                    style={{
                        marginLeft: 15,
                        height: 1,
                        backgroundColor: "#ccc",
                        transform: [{ scaleY: 0.5 }]
                    }}
                />

                <TouchableOpacity
                    style={{
                        marginTop: 10,
                        marginLeft: 20,
                        marginRight: 20,
                        height: 45,
                        borderRadius: 3,
                        backgroundColor: "#4A90E2",
                        justifyContent: "center",
                        alignItems: "center"
                    }}
                    onPress={this.payMoney.bind(this)}
                >
                    <Text style={{ color: "#fff", fontSize: 14 }}>支付</Text>
                </TouchableOpacity>

                <View
                    style={{
                        flexDirection: "row",
                        marginTop: 10,
                        height: 30,
                        justifyContent: "center",
                        alignItems: "center"
                    }}
                >
                    <TouchableOpacity
                        style={{
                            marginLeft: 10,
                            justifyContent: "center",
                            alignItems: "center"
                        }}
                        onPress={this.findStore.bind(this)}
                    >
                        <Text style={{ color: "#606060", fontSize: 14 }}>
                            查看已入驻汽配商
                        </Text>
                    </TouchableOpacity>
                </View>

                <PasswordModal
                    backdrop={true}
                    ref="modal"
                    onDone={data => {
                        this._xinbaPay(data);
                    }}
                    openForgetPassword={() => {
                        //忘记支付密码
                        this.refs.modal.hide();
                        NavigationService.navigate("ForgetPayScreen");
                    }}
                />
                <View style={{ height: safeAreaBottomHeight }} />
            </View>
        );
    }

    showCompanySearchView() {
        return (
            <View
                style={{
                    zIndex: 99,
                    position: "absolute",
                    top: 60 + statusBarHeight + 50,
                    right: 0,
                    width: screenWidth,
                    height: 500,
                    backgroundColor: "#00000000"
                }}>

                <View
                    style={{
                        marginTop: 0,
                        marginLeft: 5,
                        borderRadius: 5,
                        borderWidth: 1,
                        borderColor: "#ccc",
                        width: screenWidth - 10,
                        maxHeight: 360,
                        backgroundColor: "#fff"
                    }}>
                    <ScrollView>
                        <FlatList
                            style={{ backgroundColor: "#fff" }}
                            scrollEnabled={false}
                            data={this.state.companydata}
                            horizontal={false}
                            keyExtractor={(item, index) => index.toString()}
                            renderItem={this._renderItem}
                        />
                    </ScrollView>
                </View>
                <TouchableWithoutFeedback
                    onPress={() => {
                        this.setState({
                            showCompanySearch: false
                        });
                    }}>
                    <View  style={{
                        flex:1
                    }}/>
                </TouchableWithoutFeedback>
            </View>
        );
    }

    // 清空输入框内容
    clearTextInput = () => {
        this.searchTextInput && this.searchTextInput.clear();
        this.setState({
            companyName: "",
            currentCompanyID: "",
            companydata: []
        });
        this.searchTextInput && this.searchTextInput.focus();
    };

    // 清空输入框内容
    clearMoneyTextInput = () => {
        this.MoneyTextInput && this.MoneyTextInput.clear();
        this.setState({
            money: "",
        });
        this.MoneyTextInput && this.MoneyTextInput.focus();
    };

    _renderItem = ({ item }) => (
        <MyListItem onPressItem={this._onPressItem.bind(this)} item={item} />
    );

    _onPressItem = item => {
        this.setState({
            showCompanySearch: false,
            currentCompanyID: item.companyId,
            companyName: item.companyName
        });
    };

    //获取汽配商列表数据
    _getCompanyList = text => {
        requestApi
            .queryCompany({ name: text })
            .then(res => {
                if (!res.length) {
                    Toast.show("未找到相应汽配商", 500);
                    this.setState({ showCompanySearch: false ,companydata: res});
                    return;
                }
                this.setState({ showCompanySearch: true ,companydata: res});
            })
            .catch(err => {
                Toast.show(err.msg, 500);
                this.setState({ showCompanySearch: false });
            });
    };

    //个人设置
    personSetting() {
        Keyboard.dismiss();
        let obj = this.state.token;
        if (typeof obj == "undefined" || obj == null || obj == "") {
            NavigationService.navigate("login");
        } else {
            this.props.navigation.openDrawer();
        }
    }
    //吊起支付
    payMoney() {
        const { money, currentCompanyID } = this.state;
        let obj = this.state.token;
        if (typeof obj == "undefined" || obj == null || obj == "") {
            NavigationService.navigate("login");
        } else if (
            typeof currentCompanyID == "undefined" ||
            currentCompanyID == null ||
            currentCompanyID == 0
        ) {
            Toast.show("收款方未找到");
        } else if (typeof money == "undefined" || money == null || money == 0) {
            Toast.show("请输入付款金额");
        } else if (!global.havaPayPassword) {
            //没有支付密码 跳转设置页面
            Toast.show("你没有支付密码，请设置支付密码", 500);
            NavigationService.navigate("SetPayPassword", { istohome: true });
        } else {
            this.refs.modal.show();
        }
    }

    //发起辛巴支付
    _xinbaPay = text => {
        const { money, index, currentCompanyID, companyName } = this.state;
        if (typeof text == "undefined" || text == null || text == "") {
            Toast.show("请重新输入密码", 500);
        } else {
            let sign = MD5.hex_md5(text);
            requestApi
                .xinbaPay({
                    receiveCompanyId: currentCompanyID,
                    amount: money,
                    payMode: index,
                    password: sign
                })
                .then(res => {
                    //跳转首页
                    this.setState({ companydata: res });
                    // 支付成功跳转支付结果
                    NavigationService.navigate("PayResultScreen", {
                        orderId: res.orderId,
                        money: money,
                        companyName: companyName
                    });
                })
                .catch(err => {
                    Toast.show(err.msg, 500);
                });
        }
    };

    //查看入驻汽配商
    findStore() {
        let obj = this.state.token;
        if (typeof obj == "undefined" || obj == null || obj == "") {
            NavigationService.navigate("login");
        } else {
            NavigationService.navigate("CarBusinessListScreen");
        }
    }
}

const styles = StyleSheet.create({
    titleStyle: {
        color: "#202020",
        fontSize: 15
    },
    textInputMsg: {
        zIndex: 99,
        position: "absolute"
    },
    textInputView: {
        height: 85 / 2,
        width: 85 / 2,
        borderWidth: 1,
        borderColor: "#c9c7c7",
        justifyContent: "center",
        alignItems: "center"
    },
    itemName: {
        fontSize: 16,
        color: "black"
    }
});

class MyListItem extends PureComponent {
    _onPress = () => {
        this.props.onPressItem(this.props.item);
    };

    render() {
        return (
            <View style={{ height: 40, width: "100%" }}>
                <TouchableOpacity
                    style={{
                        flexDirection: "row",
                        height: 30,
                        marginLeft: 15,
                        marginTop: 5,
                        marginRight: 15,
                        marginBottom: 5,
                        alignItems: "center",
                        justifyContent: "flex-end"
                    }}
                    onPress={this._onPress.bind(this)}
                >
                    <Text style={{ color: "#222", fontSize: 18 }}>
                        {this.props.item.companyName}
                    </Text>
                </TouchableOpacity>
                <View
                    style={{
                        marginLeft: 15,
                        height: 1,
                        backgroundColor: "#DDDDDD",
                        transform: [{ scaleY: 0.5 }]
                    }}
                />
            </View>
        );
    }
}

export default connect(
    ({ userInfo }) => ({
        userInfo
    }),
    {}
)(HomeScreen);
